import { View, Text, Picker, Input, Textarea } from "@tarojs/components";
import { Component, ReactNode } from "react";
import { AtButton, AtList, AtListItem, AtNavBar } from "taro-ui";
import "./index.scss";
import { isEmpty } from "../../utils/kit";
import Taro from "@tarojs/taro";
import { getToken } from "../../utils/auth";
import Req, { BASE_URL } from "../../utils/request";
export default class PerformanceForm extends Component {
  state = {
    year: "",
    score: "",
    outcome: "",
    filePath: "",

    fujian: [],

    state: 0,
  };
  get futuresProjectId() {
    const { router } = Taro.getCurrentInstance();
    return router?.params.pid ?? "";
  }
  get pfId() {
    const { router } = Taro.getCurrentInstance();
    return router?.params.id ?? "";
  }
  componentDidMount(): void {
    if (this.pfId) {
      Req.get("/project/performance/" + this.pfId).then((r) => {
        console.log(r);
        if (r.code === 200) {
          if (r.data.filePath) {
            console.log(r.data.filePath.split(","));
            this.setState({
              fujian: r.data.filePath.split(","),
            });
          }
          this.setState({
            year: r.data.year ?? "",
            score: r.data.score,
            outcome: r.data.outcome,
            state: r.data.state,
          });
        }
      });
    }
  }
  uploadFujian = async (files = []) => {
    let results: any[] = [];
    const token = getToken();
    for (const file of files) {
      if (typeof file === "string") {
        results.push({
          fileName: file,
        });
        continue;
      }
      const formData = new FormData();
      formData.append("file", file);
      const response = await fetch(`${BASE_URL}/common/upload`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: formData,
      });
      let r = await response.json();
      results.push(r);
    }
    return results;
  };
  onSub = (state = 1) => {
    const { year, score, outcome, fujian } = this.state;
    if(isEmpty(year)){
      Taro.showToast({
        title: "评价年度不能为空！",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if(isEmpty(score)){
      Taro.showToast({
        title: "评价得分不能为空！",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if(isEmpty(outcome)){
      Taro.showToast({
        title: "评价结果不能为空！",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (this.futuresProjectId) {
      this.uploadFujian(fujian).then((r) => {
        let url = "/project/performance/add";
        if (this.pfId) {
          url = "/project/performance/edit";
        }
        Req.post(url, {
          year,
          futuresProjectId: this.futuresProjectId,
          type: 1,
          score,
          outcome,
          filePath: r.map((e) => e.fileName).join(","),
          state,
          ...(!isEmpty(this.pfId) && {
            id: this.pfId,
          }),
        }).then((r) => {
          if (r.code === 200) {
            Taro.navigateBack();
          }
        });
      });
    }
  };

  render(): ReactNode {
    const { year, score, outcome, fujian, state } = this.state;
    return (
      <View>
        <AtList>
          <Picker
            mode="date"
            value={year}
            fields="year"
            onChange={(e) => {
              this.setState({
                year: e.detail.value,
              });
            }}
          >
            <AtListItem
              title={"评价年度"}
              className="form-list-item form-label-required"
              arrow="down"
              note={
                <View>
                  <Text>{isEmpty(year) ? "请选择年份" : year + "年"}</Text>
                </View>
              }
            />
          </Picker>

          <AtListItem
            title={"评价类型"}
            className="form-list-item form-label-required"
            note={
              <View>
                <Text>自评</Text>
              </View>
            }
          />
          <AtListItem
            title={"评价得分"}
            className="form-list-item  no-active-effect-item form-label-required"
            note={
              <View>
                <Input
                  type="digit"
                  value={score}
                  onInput={(e) => {
                    this.setState({
                      score: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
              </View>
            }
          />
          <AtListItem
            title={"评价结果"}
            className="form-list-item no-active-effect-item remark-form-item no-arrow-space form-label-required"
            note={
              <View>
                <Textarea
                  value={outcome}
                  onInput={(e) => {
                    this.setState({
                      outcome: e.detail.value,
                    });
                  }}
                  className="remark-textarea"
                  placeholder="请输入"
                />
              </View>
            }
          />
          <AtListItem
            title={"评价报告"}
            className="form-list-item  no-active-effect-item"
            note={
              <View className="pj-box">
                <label for="fileInput">
                  <AtButton size="small">选择文件</AtButton>
                </label>
                <View>
                  {fujian.map((e: string | any, i) => (
                    <View key={i} className="fileName">
                      {typeof e === "string" ? e : e.name}
                    </View>
                  ))}
                </View>
                <input
                  id="fileInput"
                  style={{
                    display: "none",
                  }}
                  type="file"
                  multiple
                  onChange={(e: any) => {
                    const files = Array.from(e.target.files);
                    console.log(e.target.files);
                    this.setState({
                      fujian: files,
                    });
                  }}
                />
              </View>
            }
          />
        </AtList>
        <View>
          {!isEmpty(this.pfId) && state == 0 && (
            <AtButton
              onClick={() => {
                Taro.showModal({
                  title: "提示",
                  content: "确认删除？",
                  success: (res) => {
                    if (res.confirm) {
                      Req.post("/project/performance/" + this.pfId).then(
                        (r) => {
                          if (r.code === 200) {
                            Taro.navigateBack();
                          }
                        }
                      );
                    }
                  },
                });
              }}
              className="btn-performance"
              size="small"
            >
              删除
            </AtButton>
          )}

          {state == 0 && (
            <AtButton
              onClick={(e) => {
                this.onSub(0);
              }}
              className="btn-performance"
              type="primary"
              size="small"
            >
              暂存
            </AtButton>
          )}
          {state == 0 && (
            <AtButton
              onClick={(e) => {
                this.onSub(1);
              }}
              className="btn-performance"
              type="primary"
              size="small"
            >
              提交
            </AtButton>
          )}
        </View>
      </View>
    );
  }
}
